package com.example.demo.service;

import com.example.demo.codegenerate.domain.JeecgColumn;
import com.example.demo.codegenerate.util.CodeGenerateUtil;
import com.example.demo.dao.Creation;
import com.example.demo.dao.SysDicItemDao;
import com.example.demo.domain.SysDic;
import com.example.demo.dao.SysDicDao;
import com.example.demo.domain.SysDicItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class SysDicService extends BaseService<SysDic, SysDicDao>{

    private Map<String, SysDic> repository = new HashMap<String, SysDic>();

    @Autowired
    private SysDicDao sysDicDao;

    @Autowired
    private SysDicItemDao sysDicItemDao;

    @PostConstruct
    private void initRepository(){
        List<SysDicItem> items = sysDicItemDao.search();
        List<SysDic> dics = sysDicDao.search();

        dics.forEach(dic -> {
            dic.setItems(
                items.stream().filter(item -> {
                    return dic.getId().equals(item.getDicId());
                }).collect(Collectors.toList()));
            repository.put(dic.getCode(), dic);
        });
    }

    public SysDic getSysDic(String code){
        return repository.getOrDefault(code, new SysDic());
    }

    @Override
    public void delete(String id) {
        SysDic sysDic = super.get(id);
        super.delete(id);
        sysDicItemDao.deleteByCreations(new Creation("dic_id", Creation.Operation.eq, id));
        if(sysDic != null){
            repository.remove(sysDic.getCode());
        }
    }

    @Override
    public void insert(SysDic sysDic) {
        if(!StringUtils.isEmpty(sysDic.getId())){
            sysDicItemDao.deleteByCreations(new Creation("dic_id", Creation.Operation.eq, sysDic.getId()));
            super.update(sysDic);
        }else{
            sysDic.setId(UUID.randomUUID().toString());
            super.insert(sysDic);
        }

        for (SysDicItem item : sysDic.getItems()) {
            if(StringUtils.isEmpty(item.getId())){
                item.setId(UUID.randomUUID().toString());
            }
            item.setDicId(sysDic.getId());
        }

        sysDicItemDao.batchInsert(sysDic.getItems());
        repository.put(sysDic.getCode(), sysDic);
    }
}